package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.ktwlsoft.archivemanage.domain.business.repositoryService.NotifySetRepositoryService;
import com.ktwlsoft.archivemanage.domain.business.repositoryService.OperationRepositoryService;
import com.ktwlsoft.archivemanage.domain.dao.entity.Account;
import com.ktwlsoft.archivemanage.domain.dao.entity.NotifySet;
import com.ktwlsoft.archivemanage.domain.dao.entity.OperationLog;
import com.ktwlsoft.archivemanage.payload.exception.BusinessException;
import com.ktwlsoft.archivemanage.payload.notifySet.AnnualReportRemindSetRequest;
import com.ktwlsoft.archivemanage.payload.operationLog.SaveLogRequest;
import com.ktwlsoft.archivemanage.service.security.UserPrincipal;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

@Service
public class NotifySetService {
    private final NotifySetRepositoryService notifySetRepositoryService;

    public NotifySetService(NotifySetRepositoryService notifySetRepositoryService) {
        this.notifySetRepositoryService = notifySetRepositoryService;
    }

    @Transactional(rollbackFor = Exception.class)
    public void setAnnualReportNotifySet(AnnualReportRemindSetRequest request) {
        NotifySet notifySet = new NotifySet();
        try {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date timeTo = dateFormat.parse(String.format("2000-%s-%s", request.getCurrentMonths(), request.getCurrentDays()));
            long rightTime = timeTo.getTime() - request.getBeforeDays() * 24 * 60 * 60 * 1000;
            notifySet = notifySetRepositoryService.findByName("REPORT_ANNUAL");
            notifySet.setNotifyTo(timeTo);
            notifySet.setNotifyFrom(dateFormat.parse(dateFormat.format(rightTime)));
            notifySet.setNotifyPeriod(request.getIntervalDays());
            notifySet.setNotifyPeriodUnit(NotifySet.PeriodUnit.DAY);
            notifySetRepositoryService.updateSet(notifySet);
        }catch (Exception ex) {
            throw new BusinessException(ex.getMessage());
        }
        OperationRepositoryService.saveLog(new SaveLogRequest(OperationLog.OperationType.SET,
                "更改了报送提醒设置",
                "年度报送",
                OperationLog.BusinessType.BUSINESS));
    }

    public NotifySet getNotifySet(String notifySetName) {
        return notifySetRepositoryService.findByName(notifySetName);
    }
}
